package com.yc.config;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.common.base.Throwables;

import javax.servlet.http.HttpServletRequest;

import java.util.Arrays;

/**
 * 日志切面
 *
 * @author 库卡哈
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Pointcut("execution(public * com.yc.controller.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void deBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : "
                + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        log.info("方法的返回值 : " + ret);
    }

    /**
     * 后置异常通知
     *
     * @param jp
     * @param e
     */
    @AfterThrowing(pointcut = "webLog()", throwing = "e")
    public void errThrows(JoinPoint jp, Throwable e) {
        log.info("方法异常时执行.....");
        String methodName = jp.getSignature().getDeclaringTypeName() + "."
                + jp.getSignature().getName();
        log.info("请求异常：请求方法：{}, 异常信息：{}" + methodName + "  "
                + Throwables.getStackTraceAsString(e));

    }

    /**
     * 后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
     *
     * @param jp
     */
    @After("webLog()")
    public void after(JoinPoint jp) {
        log.info("方法最后执行.....");
    }

    /**
     * 环绕通知,环绕增强，相当于MethodInterceptor
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("方法环绕start.....");
        try {
            Object o = pjp.proceed();
            log.info("方法环绕proceed，结果是 :" + o);
            return o;
        } catch (Throwable e) {
            throw e;
        }
    }
}